package com.baiyi.cloud.platform.tools.service.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.baiyi.cloud.platform.commons.PageResult;
import com.baiyi.cloud.platform.tools.dao.SysBwIpDao;
import com.baiyi.cloud.platform.tools.model.SysBwIp;
import com.baiyi.cloud.platform.tools.service.SysBwIpService;


@Service
public class SysBwIpServiceImpl  implements SysBwIpService {

    @Autowired
    private SysBwIpDao sysBwIpDao;

    private static final String BIP = "TOOLSBIP" ;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate ;

	
    /**
     * 添加
     * @param sysBwIp
     */
    public int save(SysBwIp sysBwIp){
        return sysBwIpDao.save(sysBwIp);
    }

    /**
     * 修改
     * @param sysBwIp
     */
    public int update(SysBwIp sysBwIp){
        return sysBwIpDao.update(sysBwIp);
    }


    /**
     * 删除
     * @param id
     */
    public int delete(Long id){
        return sysBwIpDao.delete(id);
    }


    /**
     * 列表
     * @param params
     * @return
     */
    public PageResult<SysBwIp> findAll(Map<String, Object> params){
        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        if (MapUtils.getInteger(params, "page")!=null && MapUtils.getInteger(params, "limit")!=null)
            PageHelper.startPage(MapUtils.getInteger(params, "page"),MapUtils.getInteger(params, "limit"),true);
        
        //每次查询更新黑名单缓存
        List<SysBwIp> list  =  sysBwIpDao.findAll(params);
        if (!list.isEmpty()) {
        	redisTemplate.delete(BIP); //先从缓存删除key，然后重置ip
        	for (SysBwIp ip : list) {
        		redisTemplate.opsForSet().add(BIP, ip.getIp());
        	}
        }
        
        PageInfo<SysBwIp> pageInfo = new PageInfo(list);

        return PageResult.<SysBwIp>builder().data(pageInfo.getList()).code(0).count(pageInfo.getTotal()).build();
    }

}
